package com.xms.security.service.sitemap;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xms.core.exception.XmsException;
import com.xms.datacore.service.CreaterService;
import com.xms.security.entity.Privilege;
import com.xms.utils.UUIDUtil;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.Collection;

/**
 * <p>
 * PrivilegeCreaterService
 * </p>
 *
 * @author migo
 * @since 2021/10/2
 */
@CacheConfig(cacheNames = "privilege", keyGenerator = "CacheKeyGenerator")
@Service
public class PrivilegeCreaterService extends CreaterService<Privilege> implements IPrivilegeCreaterService {

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Override
    public boolean create(Privilege entity) throws SQLException, XmsException {
        //设置level
        if(UUIDUtil.isEmpty(entity.getParentprivilegeid())){
            entity.setLevel(1);
            entity.setParentprivilegeid(UUIDUtil.Empty);
        }
        else{
            Privilege parent = super.getById(entity.getParentprivilegeid());
            if(parent == null){
                throw new XmsException("上级节点不存在");
            }
            entity.setLevel(parent.getLevel() + 1);
        }
        //设置displayorder
        if(entity.getDisplayorder() == null){
            //同层次元素的最大值
            LambdaQueryWrapper<Privilege> queryWrapper = new LambdaQueryWrapper<>();
            //queryWrapper.select(Privilege::getDisplayorder);
            queryWrapper.eq(Privilege::getParentprivilegeid, entity.getParentprivilegeid());
            queryWrapper.orderByDesc(Privilege::getDisplayorder).last("limit 1");
            Privilege maxPrv = super.getOne(queryWrapper);
            if(maxPrv != null){
                entity.setDisplayorder(maxPrv.getDisplayorder() + 1);
            }
            else{
                entity.setDisplayorder(0);
            }
        }
        return super.save(entity);
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean createMany(Collection<Privilege> entityList) throws SQLException, XmsException {
        for (Privilege entity : entityList){
            this.create(entity);
        }
        return true;
    }
}
